<?php
namespace App\Http\Controllers\Store;

use App\Exceptions\ApiException;
use App\Http\Requests\StoreInfoRequest;
use App\Http\Requests\StoreShippingRequest;
use App\Http\Requests\StoreStatisticsRequest;
use App\Models\ShopOrder;
use App\Models\ShopOrderAppraise;
use App\Models\ShopOrderSplit;
use App\Models\LogStoreStatistics;
use App\Models\ShopGoodsScore;
use App\Models\LogStoreView;
use App\Models\ShopStore;

use App\Models\ShopStoreClass;
use App\Models\ShopStoreInfoImage;
use App\Http\Requests\BasicRequest;
use App\Models\ClientUser;
use App\Models\ClientUserMessage;
use App\Models\AdvanceImg;
use Illuminate\Support\Facades\DB;

class IndexController extends CommonController {

    //首页接口  1、当前状态与结束时间，订单信息、本月收入 2、修改商家信息 3、未处理订单 5、店铺数据 6个人消息
    public function index(BasicRequest $request){
        $store_info = $this->store;
        $return = array();
        $time = date('H:i');
        $work_start_time=date('H:i',strtotime($store_info->work_start_time)) ;
        $work_end_time=date('H:i',strtotime($store_info->work_end_time)) ;

        $return['status']=0;
        if($store_info->is_open==1) {
            if ($time > $work_start_time && $time < $work_end_time) {
                $return['status'] = 1;
            }
        }
        $return['view_num'] = LogStoreView::where(['store_id'=>$this->store_id])->count();
        $return['order_num'] = ShopOrder::where(['store_id'=>$this->store_id])->count();
        $return['month_amount'] = ShopOrderSplit::where(['store_id'=>$this->store_id])->whereIn('status',[1,2])
            ->where('created_at','>=',date('Y-m').'-01 00:00:00')
            ->sum('store_amount');
        $score = ShopOrderAppraise::getSoreNum($this->store_id);
        $return['score'] = $score?:0;
        $return['store_type'] = $store_info->store_type;
        $return['order'] = ShopOrder::getOrderStatus($store_info->store_type,$this->store_id);
        $return['image'] = AdvanceImg::where(['mobile_type'=>'store_index'])->orderBy('sort','desc')->get();
        $return['avatar'] = ClientUser::where(['id'=>$this->uid])->value('avatar');
        $return['store_name'] = $store_info->store_name;
        $return['store_logo'] = $store_info->store_logo;
		$return['message_unview_count'] = group99(ClientUserMessage::where(['uid'=>$this->uid,'viewed'=>0])->count());
        return json_success('OK',$return);
    }
	
	//查看店铺信息
	public function get_info(){
		$return['shipping_amount'] = $this->store->shipping_amount;
		$return['store_name'] = $this->store->store_name;
		$return['store_class'] = ShopStoreClass::where('id','=',$this->store->store_class)->value('store_class_name');
		$return['work_start_time'] = $this->store->work_start_time;
		$return['store_mobile'] = $this->store->store_mobile;
		$return['work_end_time'] = $this->store->work_end_time;
		$return['address'] = $this->store->address;
		$return['store_logo'] = $this->store->store_logo;
		$return['is_open'] = $this->store->is_open;
		$return['store_info'] = $this->store->store_info;
		$return['shipping_amount'] = $this->store->shipping_amount;
		$return['start_amount'] = $this->store->start_amount;
		$return['average_amount'] = $this->store->average_amount;
		$return['send_time'] = $this->store->send_time;
		$return['area_id'] = $this->store->area_id;
		$return['lat'] = $this->store->lat;
		$return['lng'] = $this->store->lng;
		$return['village_ids'] = $this->store->village_ids;
		$return['store_info_img'] = ShopStoreInfoImage::where(['store_id'=>$this->store_id])->select('id','image')->orderBy('sort','desc')->limit(5)->get();
		return json_success('OK',$return);
	}

	//修改店铺信息
	public function edit_info(StoreInfoRequest $request){
        $update=array(
            'work_start_time'=>$request->input('work_start_time'),
            'work_end_time'=>$request->input('work_end_time'),
            'store_logo'=>$request->input('store_logo'),
            'store_info'=>$request->input('store_info'),
            'store_mobile'=>$request->input('store_mobile'),
            'is_open'=>$request->input('is_open'),
        );
        array_filter($update);//清除空值
        $store_info_img = $request->input('store_info_img');
        $return=DB::transaction(function () use($update,$store_info_img) {
            ShopStore::where(['id' => $this->store_id])->update($update);
            $store_info_img = explode('|',$store_info_img);
            ShopStoreInfoImage::where(['store_id'=>$this->store_id])->delete();
            foreach ($store_info_img as $key=>$val) {
                ShopStoreInfoImage::create([
                    'store_id'=>$this->store_id,
                    'image'=>$val,
                ]);
            }
            return 'success';
            
        });
        if($return) {
            return json_success('修改成功');
        }else{
            return json_error('修改失败');
        }
	}
	//修改运费设置
    public function edit_shipping(StoreShippingRequest $request){
	    $update=array(
	        'shipping_amount'=>$request->input('shipping_amount'),
	        'start_amount'=>$request->input('start_amount'),
	        'average_amount'=>$request->input('average_amount'),
            'send_time'=>$request->input('send_time'),
            'village_ids'=>$request->input('village_ids')
        );
        $update = ShopStore::where(['id' => $this->store_id])->update($update);
        if($update) {
            return json_success('修改成功');
        }else{
            return json_error('修改失败');
        }
    }
    //店铺统计
	public function statistics(StoreStatisticsRequest $request){
	    $pram = $request->input('pram');
	    $time = $request->input('time',date('Y-m'));

        $return = array();
        if(in_array($pram,['view_num','order_num','amount_num'])){
            $return['all'] = LogStoreStatistics::where('day','like',$time.'%')->sum($pram);
            $return['date'] = LogStoreStatistics::select('id','day',$pram)->where('day','like',$time.'%')->where('store_id','=',$this->store_id)->orderBy('day','desc')->get();
            if(date('H')>'01'){
                $function = 'get_'.$pram;
                $today_num = $this->$function();
                $return['all'] +=$today_num;
                $return['date']->prepend(['id'=>0,'day'=>date('Y-m-d'),$pram=>$today_num]);
            }
        }else if($pram == 'score_num'){
            $all_score=ShopGoodsScore::where(['store_id'=>$this->store_id])->sum('score');
            $num = ShopGoodsScore::where(['store_id'=>$this->store_id])->count();
            $return['all'] = bcdiv($all_score,$num,1)?:0;
            $return['date'] = LogStoreStatistics::select('id','day','star_num as score_num')->where('day','like',$time.'%')->where('store_id','=',$this->store_id)->orderBy('day','desc')->get();
            if(date('H')>'01'){
                $return['date']->prepend(['id'=>0,'day'=>date('Y-m-d'),$pram=>$return['all']]);
            }
        }else{
            return json_error('参数错误！');
        }

        return json_success('OK',$return);
    }

    /**
     * 获得今日数据
     */
    private function get_view_num(){
        return LogStoreView::where(['store_id'=>$this->store_id,'date'=>date('Y-m-d')])->count();
    }
    private function get_order_num(){
        return ShopOrder::where(['store_id'=>$this->store_id])->where('created_at','>=',date('Y-m-d'.' 00:00:00'))->count();
    }
    private function get_amount_num(){
        return ShopOrderSplit::where(['store_id'=>$this->store_id,'status'=>2])->where('updated_at','>=',date('Y-m-d'.' 00:00:00'))->sum('store_amount');
    }
}